Ext.namespace("yft.posPurchaseOrder_form");

function getCompetenceForPosPurchaseReceipt(isAdd){
	if(isAdd == true){
		return getCompetenceForAllDev(posPurchaseOrder_authArray_1,authId[852]);
	}else{
		return getCompetenceForAllDev(posPurchaseOrder_authArray_1,authId[852]);
	}
}

function clearSessionPurchaseOrderItem(){
	Ext.Ajax.request({
		url : basepath+'/yft/posPurchaseOrder/clearSessionPurchaseOrderItem.html',
		callback:function(options,success,response){
			posPurchaseOrderItemStore_1.load();
		}
	});
}
var posPurchaseOrderItemCol_1 ='';
var fm = Ext.form;
yft.posPurchaseOrder_form.posPurchaseOrderForm = Ext.extend(Ext.Panel, {
	closable : true,
	autoScroll : true,
	layout : "fit",
	bodyStyle: my_scroll_cs,
	canClose : false,
	initComponent : function() {
		yft.posPurchaseOrder_form.posPurchaseOrderForm.superclass.initComponent.call(this);
		var mydata = this.data;
		
		var headHeight = 56;
		var purchaseOrderHeaderId;
		var isAdd = true;
		if(this.data){
			isAdd = false;
			purchaseOrderHeaderId=mydata[0].id;
		}
		
		var checkBoxId='';
		if(isAdd)
			checkBoxId = "p_posPurchaseOrderDetail_C_add";
		else
			checkBoxId = "p_posPurchaseOrderDetail_C_upd";
		
		posPurchaseOrderItemCol_1 =[
			{header:'<input type="checkbox" style="height:15" id="p_'+checkBoxId+'" name="p_'+checkBoxId+'" onClick="checkBoxAll(this)"/>',width:50,dataIndex:'index',sortable:false,align:'center',renderer:function(value, cellmeta, record, rowIndex){
					return'<input value="'+value+'" type="checkbox" style="height:15" name="'+checkBoxId+'" onClick="checkBoxSingle(this)">';}}
            ,{header:'终端序列号',dataIndex:'machineSnCode',align:"center",sortable:true}
            ,{header:'终端号',dataIndex:'terminalSn',align:"center",sortable:true}
            ,{header:'密码键盘号',dataIndex:'passwordKeySn',align:"center",sortable:true}
//            ,{header:'sim卡编号',dataIndex:'simSn',align:"center",sortable:true}
            ,{header:'机型',dataIndex:'pattern',align:"center",sortable:true}
            ,{header:'型号',dataIndex:'modelName',align:"center",sortable:true}
            ,{header:'数量',dataIndex:'quality',align:"center",sortable:true}
		];
		
		var toolBar = [];
		
		if(getCompetenceForPosPurchaseReceipt(isAdd)){
			toolBar.push('-');
			toolBar.push({
				iconCls : 'save',
				id : 'posPurchaseOrderFormSaveButton',
				text : '保存',
				pressed : false,
				handler : function(){
					if(posPurchaseOrderItemStore_1.data.length == 0){
						Ext.Msg.alert("提示", "对不起,订单内商品数量不能为空");
					}else{
						Ext.MessageBox.confirm("提示","您确认要保存当前订单信息吗?",function(o){
							if(o =='yes'){
								Ext.getCmp('posPurchaseOrderFormSaveButton').disable();
								showProgress();
                                if(isAdd){
                                    if(!headPanel.form.isValid()){
                                        Ext.MessageBox.hide();
                                        Ext.Msg.alert('提示','请正确填写订单数据');
                                        Ext.getCmp('transOrderFormSaveButton').enable();
                                    }else{
                                        headPanel.form.submit({
                                            waitTitle : '请稍候',
                                            waitMsg : '正在保存......',
                                            params:{
                                                supplyChannelId:Ext.getCmp("supplyChannel_ComboId").getValue()
                                            },
                                            url :basepath+"/yft/posPurchaseOrder/addPosPurchaseOrder.html",
                                            success : function(form, action) {
                                                Ext.MessageBox.hide();
                                                Ext.MessageBox.alert("系统消息", '恭喜您！操作已成功！', function(btn) {
                                                    showProgress();
                                                    Ext.getCmp('posPurchaseOrderFormSaveButton').enable();
                                                    headPanel.form.reset();
                                                    if(posPurchaseOrderHeaderStore)
                                                        posPurchaseOrderHeaderStore.reload();
                                                    clearSessionPurchaseOrderItem();
                                                }, this);
                                            },
                                            failure : function(form, action) {
                                                Ext.MessageBox.hide();
                                                Ext.getCmp('posPurchaseOrderFormSaveButton').enable();
                                                var m =Ext.decode(action.response.responseText);
                                                Ext.MessageBox.alert("错误",m.error);
                                            },
                                            scope : this
                                        });
                                    }
                                }else{
                                    if(!headPanel.form.isValid()){
                                        Ext.MessageBox.hide();
                                        Ext.Msg.alert('提示','请正确填写订单数据');
                                        Ext.getCmp('posPurchaseOrderFormSaveButton').enable();
                                    }else{
                                        headPanel.form.submit({
                                            waitTitle : '请稍候',
                                            params:{purchaseOrderHeaderId:purchaseOrderHeaderId},
                                            waitMsg : '正在保存......',
                                            url :basepath+"/yft/posPurchaseOrder/doUpdatePosPurchaseOrder.html",
                                            success : function(form, action) {
                                                Ext.MessageBox.hide();
                                                Ext.MessageBox.alert("系统消息", '恭喜您！操作已成功！', function(btn) {
                                                    Ext.MessageBox.hide();
                                                    if(posPurchaseOrderHeaderStore){
                                                        posPurchaseOrderHeaderStore.reload();
                                                    }
                                                    main.remove(main.getComponent("newTab_purchaseOrderUpdate"));
                                                }, this);
                                            },
                                            failure : function(form, action) {
                                                Ext.MessageBox.hide();
                                                Ext.getCmp('posPurchaseOrderFormSaveButton').enable();
                                                var m =Ext.decode(action.response.responseText);
                                                Ext.MessageBox.alert("错误",m.error);
                                            },
                                            scope : this
                                        });
                                    }
                                }
							}
						});
					}
				},
				scope : this
			});
			toolBar.push('-');
			toolBar.push({
				iconCls : 'add',
				text : '添加Pos',
				pressed : false,
				handler : function(){
                    var supplyChannelId;
                    if(isAdd){
                        supplyChannelId = Ext.getCmp('supplyChannel_ComboId').getValue();
                        if(supplyChannelId==null){
                            Ext.MessageBox.alert("错误","请先选择进货渠道");
                            return;
                        }
                    }else{
                        supplyChannelId = mydata[0].supplyChannelId;
                    }

					if(Ext.getCmp('addposPurchaseOrderItemWindow')){
						Ext.getCmp('addposPurchaseOrderItemWindow').show()
						Ext.getCmp('addposPurchaseOrderItemWindow').setPosition(mainPanelWidth/7+8,138);
					}else{
                        var posModel_Combo = new Ext.pos_public.posModel_Combo();
                        var store = posModel_Combo.getStore();
                        store.baseParams['supplyChannelId'] = supplyChannelId;
                        posModel_Combo.on('select',function(com,record,index){
                            posModel_Combo.recordIndex = index;
                        });



                        var tablePanel = new Ext.form.FormPanel({
//							frame : true,
                            height : 110,
                            bodyStyle:'background-color:#DFE8F6;border:0px solid #DFE8F6;',
                            defaults:{bodyStyle:'background-color:#DFE8F6;border:0px solid #DFE8F6;'},
                            layout:"table",
                            layoutConfig: {
                                columns:7
                            },
                            items : [
                                {height : 15,colspan:7},
                                {width : 5},
                                {html : '<span style="font-size:12px;color:red;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pos机型:</span>&nbsp;&nbsp;'},
                                posModel_Combo,
                                {width : 20},
                                {html : '<span style="font-size:12px;color:red;">终端序列号:</span>&nbsp;&nbsp;'},
                                {
                                    xtype:'textfield',
                                    id:'machineSnCodeId',
                                    allowBlank : false,
                                    name:'machineSnCode'
                                },
                                {width : 5},
                                {height : 10,colspan:7},
                                {width : 5},
                                {html : '<span style="font-size:12px;color:red;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;终端号:</span>&nbsp;&nbsp;'},
                                {
                                    xtype:'textfield',
                                    id:'terminalSnId',
                                    allowBlank : false,
                                    width: 240,
                                    name:'terminalSn'
                                },
                                {width : 20},
                                {html : '<span style="font-size:12px;color:red;">密码键盘号:</span>&nbsp;&nbsp;'},
                                {
                                    xtype:'textfield',
                                    id:'passwordKeySnId',
                                    allowBlank : false,
                                    name:'passwordKeySn'
                                },
                                {width : 5 }
                            ]
                        });

                        var flff = '';
                        if(isAdd)
                            flff = 1;
                        else
                            flff = 0;
                        var addDetail = function(needCloseWin){
                            showProgress();
                            var store = posModel_Combo.getStore();
                            var posModelRecord = store.getAt(store.find('id',posModel_Combo.getValue()));
                            if(posModelRecord==null){
                                Ext.MessageBox.alert("提示","请选择机型");
                            }
                            if(!tablePanel.form.isValid()){
                                Ext.MessageBox.hide();
                                Ext.Msg.alert('提示','请正确填写数据');
//                                Ext.getCmp('positionAdjustReceiptFormSaveButton').enable();
                            }else{
                                tablePanel.form.submit({
                                    waitTitle : '请稍候',
                                    waitMsg : '正在保存......',
                                    params:{
                                        posModelId : posModel_Combo.getValue(),
                                        pattern : posModelRecord.data.pattern,
                                        modelName : posModelRecord.data.modelName,
                                        isAdd : flff
                                    },
                                    url : basepath+'/yft/posPurchaseOrder/addPurchaseOrderItemToSession.html',
                                    success : function(form, action) {
                                        Ext.MessageBox.hide();
                                        Ext.MessageBox.alert("系统消息", '恭喜您！操作已成功！', function(btn) {
                                            posPurchaseOrderItemStore_1.reload();
                                            tablePanel.form.reset();
                                            if(needCloseWin)
                                                win.close();
                                        }, this);
                                    },
                                    failure : function(form, action) {
                                        Ext.MessageBox.hide();
                                        var mess="对不起,系统异常,请稍候再试!";
                                        var m =Ext.decode(action.response.responseText);
                                        if(m.error){
                                            mess=m.error;
                                        }
                                        Ext.MessageBox.alert("提示",mess);
                                    },
                                    scope : this
                                });
                            }
                        }
                        var fff = function(needCloseWin){
                            if(tablePanel.form.isValid()){
                                var posModelId = posModel_Combo.getValue();
                                var machineSnCode = Ext.getCmp('machineSnCodeId').getValue();
                                var terminalSn = Ext.getCmp('terminalSnId').getValue();
                                var passwordKeySn = Ext.getCmp('passwordKeySnId').getValue();
                                if(posPurchaseOrderItemStore_1.getTotalCount()>0){
                                    posPurchaseOrderItemStore_1.each(function(record){
                                        if(record.data.posModelId==posModelId || record.data.machineSnCode==machineSnCode ||  record.data.passwordKeySn==passwordKeySn || (terminalSn!='' && record.data.terminalSn!='' && terminalSn==record.data.terminalSn)){
                                            Ext.MessageBox.alert("提示","数据已存在录入重复");
                                            return false;
                                        }else{
                                            addDetail(needCloseWin);
                                        }
                                    });
                                }else{
                                    addDetail(needCloseWin);
                                }
                            }
                        }

                        var order_add_btn1 = new Ext.Button({
                            text : '添加并继续',
                            handler : function(){
                                fff(false);
                            },
                            width : 100
                        });
                        var order_add_btn2 = new Ext.Button({
                            text : '添加并关闭',
                            handler : function(){
                                fff(true);
                            },
                            width : 100
                        });
                        var order_add_btn3 = new Ext.Button({
                            text : '关闭',
                            handler : function(){
                                win.close();
                            },
                            width : 100
                        });

                        var win =new Ext.Window({
                            title:'pos机添加',
                            frame : true,
                            width: 650,
                            height: 180,
                            items : tablePanel,
                            minimizable: false,
                            maskDisabled: true,
                            resizable: false,
                            autoScroll: false,
                            draggable: true,
                            modal: true,
                            buttons:[
                                order_add_btn1,
                                order_add_btn2,
                                order_add_btn3
                            ]
                        });
                        win.show();
                        win.setPosition(174,138);
						
					}
				},
				scope : this
			});
			
			toolBar.push('-');
			toolBar.push({
				iconCls : 'del',
				text : '删除pos机',
				pressed : false,
				handler : function(){
					var prop = '';
					var tparams;
					for (var i = 0; i < document.getElementsByName(checkBoxId).length; i++) {
						if(document.getElementsByName(checkBoxId)[i].checked==true)
							prop += document.getElementsByName(checkBoxId)[i].value+",";
					}
					if(prop != ''){
						Ext.MessageBox.confirm("提示","您确认要删除当前选中pos机吗?",function(o){
							if(o =='yes'){
								if(isAdd)
									tparams = {indexsInSession : prop};
								else
									tparams = {idsForUpdate : prop};
								showProgress();
								Ext.Ajax.request({
									url : basepath+'/yft/posPurchaseOrder/deletePosItemInSessionForP.html',
									params : tparams,
									callback:function(options,success,response){
										var m =Ext.decode(response.responseText);
										mainMessageBox.hide();
										if(m.success){
											document.getElementById('p_'+checkBoxId).checked=false;
											posPurchaseOrderItemStore_1.reload();
										}else{
											var mess="对不起,提交失败,请稍候再试!";
											if(m.error){
												mess=m.error;
											}
											Ext.MessageBox.alert("提示",mess,function(){
												posPurchaseOrderItemStore_1.reload();
											});
										}
									}
								});
							}
						});
					}else{
						Ext.Msg.alert("提示", "对不起,请选择您要删除的pos机!");
					}
				},
				scope : this
			});
			toolBar.push('-');
			if(isAdd){
				toolBar.push({
					iconCls : 'clear',
					text : '清空数据',
					pressed : false,
					handler : function(){
						Ext.MessageBox.confirm("提示","您确认要清空所有信息吗?",function(o){
							if(o =='yes'){
                                clearSessionPurchaseOrderItem();
							}
						});
					},
					scope : this
				});
			}else{
				toolBar.push({
					iconCls : 'recover',
					text : '重置数据',
					pressed : false,
					handler : function(){
						Ext.MessageBox.confirm("提示","您确认要重置当前所有数据吗?",function(o){
							if(o =='yes'){
								Ext.Ajax.request({
									url : basepath+'/yft/posPurchaseOrder/resetSessionFreezeItem.html',
									params : {
										purchaseOrderHeaderId : purchaseOrderHeaderId
									},
									callback:function(options,success,response){
										posPurchaseOrderItemStore_1.removeAll();
										posPurchaseOrderItemStore_1.load();
										document.getElementById('p_'+checkBoxId).checked=false;
									}
								});
							}
						});
					},
					scope : this
				});
			}
			toolBar.push('-');
		}
		
		var toolBarReal = new Ext.Toolbar({
			style: topBarStyle,
			items: toolBar
		});
		
		var posPurchaseOrderItemStore_1 = new Ext.data.JsonStore({
			url:basepath+'/yft/posPurchaseOrder/getSessionPurchaseOrderItemList.html',
			root:'root',
			totalProperty:'totalProperty',
			fields:[
                {name: 'id'},
                {name: 'machineSnCode'},
                {name: 'terminalSn'},
                {name: 'passwordKeySn'},
                {name: 'pattern'},
                {name: 'index'},
                {name: 'modelName'},
                {name: 'quality'}
			]
		});
		if(!isAdd){
			posPurchaseOrderItemStore_1.baseParams['isAdd'] = '0';
		}else{
			posPurchaseOrderItemStore_1.baseParams['isAdd'] = '1';
		}
		posPurchaseOrderItemStore_1.load();
		
		var mrMenu = [];
		if(getCompetenceForPosPurchaseReceipt(isAdd)){
			mrMenu.push({
				text:"删除",
				iconCls : 'del',
				handler: function(grid ,rowIndex,cellIndex,e){
					var record = grid.getStore().getAt(rowIndex);
					Ext.MessageBox.confirm("提示","您确认要删除当前商品吗?",function(o){
						if(o =='yes'){
							if(isAdd)
								tparams = {indexsInSession : record.data.index};
							else
								tparams = {idsForUpdate : record.data.index};
							showProgress();
							Ext.Ajax.request({
								url : basepath+'/yft/posPurchaseOrder/deletePosItemInSessionForP.html',
								params : tparams,
								callback:function(options,success,response){
									var m =Ext.decode(response.responseText);
									mainMessageBox.hide();
									if(m.success){
										document.getElementById('p_'+checkBoxId).checked=false;
										posPurchaseOrderItemStore_1.reload();
									}else{
										var mess="对不起,提交失败,请稍候再试!";
										if(m.error){
											mess=m.error;
										}
										Ext.MessageBox.alert("提示",mess,function(){
											posPurchaseOrderItemStore_1.reload();
										});
									}
								}
							});
						}
					});
				}
			});
		}
		var posPurchaseOrderItemGrid = new Ext.grid.EditorGridPanel({
			autoScroll:true,
			bodyStyle:'background-color:#DFE8F6;border:0px solid #DFE8F6;',
//		  	editable : true,
            tbar : toolBarReal,
		  	myRightclickMenu: mrMenu,
			loadMask: new Ext.LoadMask(Ext.getBody(), {msg:"数据加载中..."}),
//			autoExpandColumn: 2,
			columns: posPurchaseOrderItemCol_1,
			stripeRows : true,
			store: posPurchaseOrderItemStore_1
		});

        var headPanelItems = [];
        var expressNo = new Ext.form.TextField({
            name : 'expressNo',
            labelStyle:labelStyle,
            fieldLabel : '快递单号',
            allowBlank : false,
            blankText : '快递单号为必填项',
            width : 150
        });
        if(!isAdd){
            headPanelItems = [
                {height : 10,colspan:6},
                {width : 10},
                {height : 22,html : '<span style="font-size:12px;color:red;">渠道:</span>&nbsp;&nbsp;'},
                {html : '<span style="font-size:12px;">'+mydata[0].channelName+'</span>'},
                {width : 30},
                {height : 22,html : '<span style="font-size:12px;color:red;">快递单号:</span>&nbsp;&nbsp;'},
                expressNo
            ]
            expressNo.setValue(mydata[0].expressNo);
        }else{
            var supplyChannel = new Ext.pos_public.supplyChannel_Combo({
                id:'supplyChannel_ComboId',
                name : 'supplyChannel'
            });
            headPanelItems = [
                {height : 10,colspan:6},
                {width : 10},
                {height : 22,html : '<span style="font-size:12px;color:red;">渠道:</span>&nbsp;&nbsp;'},
                supplyChannel,
                {width : 30},
                {height : 22,html : '<span style="font-size:12px;color:red;">快递单号:</span>&nbsp;&nbsp;'},
                expressNo
            ]
            supplyChannel.on('change',function(com,newValue,oldValue){
                if(!Ext.isEmpty(oldValue) &&  newValue!=oldValue){
                    Ext.MessageBox.confirm('提示','进货渠道将要改变，改变进货渠道将清空所选pos机,你确定这样做吗？',function(b){
                        if(b=='yes'){
                            clearSessionPurchaseOrderItem();
                        }else{
                            com.setValue(oldValue);
                        }
                    });
                }
            });
        }
        var headPanel = new Ext.form.FormPanel({
            height : headHeight,
            bodyStyle:'background-color:#DFE8F6;border:0px solid #DFE8F6;',
            defaults:{bodyStyle:'background-color:#DFE8F6;border:0px solid #DFE8F6;'},
            layout:"table",
            tbar : toolBarReal,
            layoutConfig: {
                columns:12
            },
            items : headPanelItems
        });

        var basePanel = new Ext.Panel({
            bodyStyle:'background-color:#DFE8F6;border:0px solid #DFE8F6;',
            autoScroll: true,
            layout : 'table',
            layoutConfig: {
                columns: 1
            },
            items: [headPanel,posPurchaseOrderItemGrid]
        });

        basePanel.on('resize',function(){
            headPanel.setWidth(basePanel.getInnerWidth());
            headPanel.setHeight(headHeight);
            posPurchaseOrderItemGrid.setWidth(basePanel.getInnerWidth());
            posPurchaseOrderItemGrid.setHeight(basePanel.getInnerHeight()-headHeight);
        });
        basePanel.on('afterlayout',function(){
            if(basePanel.getInnerWidth()>0){
                headPanel.setWidth(basePanel.getInnerWidth());
                headPanel.setHeight(headHeight);
                posPurchaseOrderItemGrid.setWidth(basePanel.getInnerWidth());
                posPurchaseOrderItemGrid.setHeight(basePanel.getInnerHeight()-headHeight);
            }
        });
        this.add(basePanel);
	}
});
